package com.miage.kangourou.server.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.miage.kangourou.client.beans.Salle;

public class SalleDao extends GenericDao<Salle> {

	public SalleDao(Connection connect) {
		super(connect);
	}

	public Salle findById(int id) throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM SALLE WHERE ID_SALLE = " + id);

		Salle salle;

		if (result.next()) {
			salle = new Salle(result.getInt("ID_SALLE"), result
					.getString("INTITULE"), result.getString("GOOGLEMAP"));
		} else {
			salle = new Salle();
		}

		result.close();

		return salle;
	}

	public List<Salle> findAll() throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM SALLE");

		List<Salle> all = new ArrayList<Salle>();
		while (result.next()) {
			all.add(new Salle(result.getInt("ID_SALLE"), result
					.getString("INTITULE"), result.getString("GOOGLEMAP")));
		}

		result.close();

		return all;
	}

	public void create(Salle salle) throws SQLException {
		if (salle instanceof Salle && !salle.equals(null)) {

			connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"INSERT INTO SALLE (ID_SALLE, INTITULE, GOOGLEMAP) VALUES ("
							+ salle.getId_salle() + ", \""
							+ salle.getIntitule() + "\", \""
							+ salle.getGoogleMap() + "\"");
		}
	}

	public boolean alreadyExist(Salle salle) throws SQLException {
		boolean exist = false;

		if (salle instanceof Salle && !salle.equals(null)) {

			ResultSet result = connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"SELECT * FROM SALLE WHERE ID_SALLE = "
							+ salle.getId_salle());

			if (result.next()) {
				exist = true;
			}

			result.close();
		}

		return exist;
	}

	public boolean delete(int idSalle) {
		boolean deleted = true;

		try {
			connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY)
					.executeQuery(
							"DELETE FROM SALLE WHERE ID_SALLE = "
							+ idSalle);
			
		} catch (SQLException e) {
			e.printStackTrace();
			deleted = false;
		}
		
		return deleted;
	}
}
